package com.weakteam.orderonline.adminconsole.web;

import com.weakteam.orderonline.dataresource.domain.ClientOrder;
import com.weakteam.orderonline.dataresource.domain.Place;
import com.weakteam.orderonline.dataresource.service.ClientOrderService;
import com.weakteam.orderonline.dataresource.service.PlaceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Nail on 09.03.14.
 */

@Controller
public class OrderNetService {

    @Autowired
    ClientOrderService orderService;

    private static final Logger log = LoggerFactory.getLogger(OrderNetService.class);

    private static void initJSONHeader(final HttpServletResponse httpResponse){
        httpResponse.setHeader("Connection", "close");
        httpResponse.setHeader("Content-Type", "application/json");
        httpResponse.setHeader("Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
        httpResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        httpResponse.setHeader("Pragma", "no-cache");
        httpResponse.setCharacterEncoding("UTF-8");
    }

    @RequestMapping(value = "/getOrdersData")
    public void getOrdersData(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) {
        try {
            initJSONHeader(httpResponse);
            PrintWriter out = httpResponse.getWriter();
            List<ClientOrder> orders = orderService.getAll();
            out.print("[");
            for (Iterator<ClientOrder> it = orders.iterator(); it.hasNext();) {
                ClientOrder order = it.next();
                out.print(order.getJSON());
                if (it.hasNext()) out.println(",");
            }
            out.print("]");
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("getOrdersData {}", ex);
        }
    }
}